package com.taoyibao.hongcanting.http.interceptor;

import android.content.Context;

import com.google.gson.Gson;
import com.taoyibao.hongcanting.http.ApiException;
import com.taoyibao.hongcanting.http.ErrorModel;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * 网络请求拦截器
 */
public class ReceivedCookiesInterceptor implements Interceptor {
    private static String TAG = ReceivedCookiesInterceptor.class.getSimpleName();
    private static boolean debug = false;
    private Context context;
    private Gson mGson = new Gson();

    public ReceivedCookiesInterceptor(Context context) {
        super();
        this.context = context;
    }

    @Override
    public Response intercept(final Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        //ResponseCode 不等于200,异常出现
        if (originalResponse.code() != 200) {
            String s = originalResponse.body().string();
            ErrorModel error = mGson.fromJson(s, ErrorModel.class);
//            LogUtils.eNormal(TAG, "http code:" + originalResponse.code() + ",error code:" + error.status + ",error message:" + error.message);
            //抛出后台返回的异常
            throw new ApiException(error.code, error.msg);
        }
        //目前没有Cookie先不用
        //这里获取请求返回的cookie
//        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
//            final StringBuffer cookieBuffer = new StringBuffer();
//            Observable.from(originalResponse.headers("Set-Cookie"))
//                    .map(new Func1<String, String>() {
//                        @Override
//                        public String call(String s) {
//                            String[] cookieArray = s.split(";");
//                            return cookieArray[0];
//                        }
//                    })
//                    .subscribe(new Action1<String>() {
//                        @Override
//                        public void call(String cookie) {
//                            cookieBuffer.append(cookie).append(";");
//                        }
//                    });
//            Log.d(TAG, "===服务器的cookie intercept: " + cookieBuffer.toString());
//            SpUtils.putCookie(cookieBuffer.toString());
//        }
        return originalResponse;
    }
}
